package com.heima.homeservicemanagementsystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.homeservicemanagementsystem.entity.*;
import com.heima.homeservicemanagementsystem.mapper.CommentFormMapper;
import com.heima.homeservicemanagementsystem.service.*;
import com.heima.homeservicemanagementsystem.utils.SensitiveWordsUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.heima.homeservicemanagementsystem.module.PageParams;
import com.heima.homeservicemanagementsystem.module.Result;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static cn.dev33.satoken.SaManager.log;

/**
 * 评论表;(comment_form)表控制层
 *
 * @author : http://www.chiner.pro
 * @date : 2025-4-22
 */
@Tag(name = "评论表对象功能接口")
@RestController
@RequestMapping("/commentForm")
public class CommentFormController {

    @Resource
    private CommentFormService commentFormService;
    @Resource
    private CommentFormMapper commentFormMapper;
    @Resource
    private WxUserService wxUserService;
    @Resource
    private CommentSensitiveTextService commentSensitiveTextService;
    @Resource
    private EmployeesAndServiceService employeesAndServiceService;
    @Resource
    private ServiceServicedetailService serviceServicedetailService;

    @Operation(summary = "分页查询")
    @PostMapping("/page")
    public Result<Page<CommentForm>> paginQuery(@RequestBody PageParams<CommentForm> pageParams) {
        //查询参数
        CommentForm params = pageParams.getParams();
        LambdaQueryWrapper<CommentForm> lqw = new LambdaQueryWrapper<>();


        lqw.eq(params.getUserId() != null, CommentForm::getUserId, params.getUserId());


        lqw.eq(params.getComprehensiveScore() != null, CommentForm::getComprehensiveScore, params.getComprehensiveScore());


        lqw.eq(params.getServiceId() != null, CommentForm::getServiceId, params.getServiceId());


        lqw.eq(params.getIsAnonymous() != null, CommentForm::getIsAnonymous, params.getIsAnonymous());


        lqw.eq(params.getParentId() != null, CommentForm::getParentId, params.getParentId());


        return Result.success(commentFormService.page(pageParams.getPage(), lqw));
    }


    @Operation(summary = "评论表所有搜索")
    @GetMapping("/list")
    public Result searchQuery() {
        List<CommentForm> list = commentFormService.list();
        for (CommentForm commentForm : list) {
            Set<String> allData = commentSensitiveTextService.getAllData();
            SensitiveWordsUtil.addBadWordToHashMap(allData);
            //过滤敏感词，替换为 *
            String zs = SensitiveWordsUtil.replaceBadWord(commentForm.getFeel(), SensitiveWordsUtil.maxMatchType, "*");
            commentForm.setFeel(zs);
            WxUser byId = wxUserService.getById(commentForm.getUserId());
            if ("true".equals(commentForm.getIsAnonymous())) {
                String username = byId.getUsername();
                String username2 = username.charAt(0) + "*";
                byId.setUsername(username2);
            }
            commentForm.setUserDetail(byId);
        }

        return Result.success(list);
    }

    @Operation(summary = "商品的单独的一个")
    @PostMapping("/sjsearch")
    public Result Query2(@RequestBody CommentForm commentForm) {

        LambdaQueryWrapper<CommentForm> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(CommentForm::getServiceId, commentForm.getServiceId()).last("ORDER BY RAND() LIMIT 1");
        List<CommentForm> commentForms = commentFormMapper.selectList(objectLambdaQueryWrapper);
        for (CommentForm form : commentForms) {
            Set<String> allData = commentSensitiveTextService.getAllData();
            SensitiveWordsUtil.addBadWordToHashMap(allData);
            //过滤敏感词，替换为 *
            String zs = SensitiveWordsUtil.replaceBadWord(form.getFeel(), SensitiveWordsUtil.maxMatchType, "*");
            form.setFeel(zs);
            WxUser byId = wxUserService.getById(form.getUserId());
            if ("true".equals(form.getIsAnonymous())) {
                String username = byId.getUsername();
                String username2 = username.charAt(0) + "*";
                byId.setUsername(username2);
            }
            form.setUserDetail(byId);

        }
        return Result.success(commentForms);

    }

    @Operation(summary = "数量")
    @PostMapping("/getcount")
    public Result getcount(@RequestBody CommentForm commentForm) {
        LambdaQueryWrapper<CommentForm> lqw = new LambdaQueryWrapper<>();
        lqw.eq(commentForm.getServiceId() != null, CommentForm::getServiceId, commentForm.getServiceId());
        lqw.eq(commentForm.getComprehensiveScore() != null, CommentForm::getComprehensiveScore, commentForm.getComprehensiveScore());
        long count = commentFormService.count(lqw);
        return Result.success(count);

    }

    @Operation(summary = "有条件的搜索手机端")
    @PostMapping("/sjSearchs")
    public Result sQuery(@RequestBody CommentForm commentForm) {
        log.info("commentForm:{}", commentForm);
        LambdaQueryWrapper<CommentForm> lqw = new LambdaQueryWrapper<>();
        lqw.eq(commentForm.getServiceId() != null, CommentForm::getServiceId, commentForm.getServiceId());

        if ("1".equals(commentForm.getComprehensiveScore())) {
            lqw.ge(CommentForm::getComprehensiveScore, 4);
        }
        if ("2".equals(commentForm.getComprehensiveScore())) {
            lqw.eq(CommentForm::getComprehensiveScore, 3);
        }
        if ("3".equals(commentForm.getComprehensiveScore())) {
            lqw.gt(CommentForm::getComprehensiveScore, 0)
                    .le(CommentForm::getComprehensiveScore, 2);
        }
        List<CommentForm> list = commentFormService.list(lqw);
        for (CommentForm form : list) {
            Set<String> allData = commentSensitiveTextService.getAllData();
            SensitiveWordsUtil.addBadWordToHashMap(allData);
            //过滤敏感词，替换为 *
            String zs = SensitiveWordsUtil.replaceBadWord(form.getFeel(), SensitiveWordsUtil.maxMatchType, "*");
            form.setFeel(zs);
            WxUser byId = wxUserService.getById(form.getUserId());
            if ("true".equals(form.getIsAnonymous())) {
                String username = byId.getUsername();
                String username2 = username.charAt(0) + "*";
                byId.setUsername(username2);
            }
            form.setUserDetail(byId);

        }

        return Result.success(list);
    }

    @Operation(summary = "从业人员的有条件的搜索手机端")
    @GetMapping("/cysjSearchs")
    public Result cysQuery(@RequestParam String userid, @RequestParam String comprehensiveScore) {
        log.info("userid:{}", userid);
        List<CommentForm> list2 = new ArrayList<>();
        List<EmployeesAndService> list = employeesAndServiceService.list(Wrappers.<EmployeesAndService>lambdaQuery().eq(EmployeesAndService::getUserId, userid));
        for (EmployeesAndService employeesAndService : list) {
            List<ServiceServicedetail> list1 = serviceServicedetailService.list(Wrappers.<ServiceServicedetail>lambdaQuery().eq(ServiceServicedetail::getServiceid, employeesAndService.getServiceId()));
            for (ServiceServicedetail serviceServicedetail : list1) {
                String detailid = serviceServicedetail.getDetailid();
                LambdaQueryWrapper<CommentForm> lqw = new LambdaQueryWrapper<>();
                lqw.eq(detailid != null, CommentForm::getServiceId, detailid);

                if ("1".equals(comprehensiveScore)) {
                    lqw.ge(CommentForm::getComprehensiveScore, 4);
                }
                if ("2".equals(comprehensiveScore)) {
                    lqw.eq(CommentForm::getComprehensiveScore, 3);
                }
                if ("3".equals(comprehensiveScore)) {
                    lqw.gt(CommentForm::getComprehensiveScore, 0)
                            .le(CommentForm::getComprehensiveScore, 2);
                }
                list2.addAll(commentFormService.list(lqw));
                for (CommentForm form : list2) {
                    Set<String> allData = commentSensitiveTextService.getAllData();
                    SensitiveWordsUtil.addBadWordToHashMap(allData);
                    //过滤敏感词，替换为 *
                    String zs = SensitiveWordsUtil.replaceBadWord(form.getFeel(), SensitiveWordsUtil.maxMatchType, "*");
                    form.setFeel(zs);
                    WxUser byId = wxUserService.getById(form.getUserId());
                    if ("true".equals(form.getIsAnonymous())) {
                        String username = byId.getUsername();
                        String username2 = username.charAt(0) + "*";
                        byId.setUsername(username2);
                    }
                    form.setUserDetail(byId);

                }
            }

        }


        return Result.success(list2);
    }

    @Operation(summary = "所有的数量")
    @PostMapping("/sjcount")
    public Result scount(@RequestBody CommentForm commentForm) {
        log.info("commentForm:{}", commentForm);

        // 定义一个数组来存储每个条件下的数量
        int[] counts = new int[4]; // 数组分别存储每个条件下的数量

        // 根据 serviceId 和 comprehensiveScore 为 "1" 时的查询条件
        LambdaQueryWrapper<CommentForm> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(commentForm.getServiceId() != null, CommentForm::getServiceId, commentForm.getServiceId());
        lqw1.ge(CommentForm::getComprehensiveScore, 4);
        counts[1] = (int) commentFormService.count(lqw1);  // 统计符合条件的数量

        // 根据 serviceId 和 comprehensiveScore 为 "2" 时的查询条件
        LambdaQueryWrapper<CommentForm> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(commentForm.getServiceId() != null, CommentForm::getServiceId, commentForm.getServiceId());
        lqw2.eq(CommentForm::getComprehensiveScore, 3);
        counts[2] = (int) commentFormService.count(lqw2);  // 统计符合条件的数量

        // 根据 serviceId 和 comprehensiveScore 为 "3" 时的查询条件
        LambdaQueryWrapper<CommentForm> lqw3 = new LambdaQueryWrapper<>();
        lqw3.eq(commentForm.getServiceId() != null, CommentForm::getServiceId, commentForm.getServiceId());
        lqw3.gt(CommentForm::getComprehensiveScore, 0)
                .le(CommentForm::getComprehensiveScore, 2);
        counts[3] = (int) commentFormService.count(lqw3);  // 统计符合条件的数量

        // 根据 serviceId 时的查询条件（不考虑 comprehensiveScore）
        LambdaQueryWrapper<CommentForm> lqw4 = new LambdaQueryWrapper<>();
        lqw4.eq(commentForm.getServiceId() != null, CommentForm::getServiceId, commentForm.getServiceId());
        counts[0] = (int) commentFormService.count(lqw4);  // 统计符合条件的数量

        // 返回结果，包含每个条件下的统计数量
        return Result.success(counts);
    }


    @Operation(summary = "从业人员所有的数量")
    @GetMapping("/cycount")
    public Result cycount(@RequestParam String userid) {
        int[] counts = new int[4]; // 数组分别存储每个条件下的数量
        List<EmployeesAndService> list = employeesAndServiceService.list(Wrappers.<EmployeesAndService>lambdaQuery().eq(EmployeesAndService::getUserId, userid));
        for (EmployeesAndService employeesAndService : list) {
            List<ServiceServicedetail> list1 = serviceServicedetailService.list(Wrappers.<ServiceServicedetail>lambdaQuery().eq(ServiceServicedetail::getServiceid, employeesAndService.getServiceId()));
            for (ServiceServicedetail serviceServicedetail : list1) {
                String detailid = serviceServicedetail.getDetailid();
                // 根据 serviceId 和 comprehensiveScore 为 "1" 时的查询条件
                LambdaQueryWrapper<CommentForm> lqw1 = new LambdaQueryWrapper<>();
                lqw1.eq(detailid != null, CommentForm::getServiceId, detailid);
                lqw1.ge(CommentForm::getComprehensiveScore, 4);
                counts[1] += (int) commentFormService.count(lqw1);  // 统计符合条件的数量

                // 根据 serviceId 和 comprehensiveScore 为 "2" 时的查询条件
                LambdaQueryWrapper<CommentForm> lqw2 = new LambdaQueryWrapper<>();
                lqw2.eq(detailid != null, CommentForm::getServiceId, detailid);
                lqw2.eq(CommentForm::getComprehensiveScore, 3);
                counts[2] += (int) commentFormService.count(lqw2);  // 统计符合条件的数量

                // 根据 serviceId 和 comprehensiveScore 为 "3" 时的查询条件
                LambdaQueryWrapper<CommentForm> lqw3 = new LambdaQueryWrapper<>();
                lqw3.eq(detailid != null, CommentForm::getServiceId, detailid);
                lqw3.gt(CommentForm::getComprehensiveScore, 0)
                        .le(CommentForm::getComprehensiveScore, 2);
                counts[3] += (int) commentFormService.count(lqw3);  // 统计符合条件的数量

                // 根据 serviceId 时的查询条件（不考虑 comprehensiveScore）
                LambdaQueryWrapper<CommentForm> lqw4 = new LambdaQueryWrapper<>();
                lqw4.eq(detailid != null, CommentForm::getServiceId, detailid);
                counts[0] += (int) commentFormService.count(lqw4);  // 统计符合条件的数量
            }

        }

        return Result.success(counts);
    }


    @Operation(summary = "有条件的搜索")
    @PostMapping("/tjSearch")
    public Result Query(@RequestBody CommentForm commentForm) {
        LambdaQueryWrapper<CommentForm> lqw = new LambdaQueryWrapper<>();


        lqw.eq(commentForm.getId() != null, CommentForm::getId, commentForm.getId());


        lqw.eq(commentForm.getUserId() != null, CommentForm::getUserId, commentForm.getUserId());


        lqw.eq(commentForm.getComprehensiveScore() != null, CommentForm::getComprehensiveScore, commentForm.getComprehensiveScore());
        lqw.like(commentForm.getFeel() != null, CommentForm::getFeel, commentForm.getFeel());


        lqw.eq(commentForm.getServiceId() != null, CommentForm::getServiceId, commentForm.getServiceId());


        lqw.eq(commentForm.getIsAnonymous() != null, CommentForm::getIsAnonymous, commentForm.getIsAnonymous());


        lqw.eq(commentForm.getParentId() != null, CommentForm::getParentId, commentForm.getParentId());
        List<CommentForm> list = commentFormService.list(lqw);
        for (CommentForm form : list) {
            Set<String> allData = commentSensitiveTextService.getAllData();
            SensitiveWordsUtil.addBadWordToHashMap(allData);
            //过滤敏感词，替换为 *
            String zs = SensitiveWordsUtil.replaceBadWord(form.getFeel(), SensitiveWordsUtil.maxMatchType, "*");
            form.setFeel(zs);
            WxUser byId = wxUserService.getById(form.getUserId());
            if ("true".equals(form.getIsAnonymous())) {
                String username = byId.getUsername();
                String username2 = username.charAt(0) + "*";
                byId.setUsername(username2);
            }
            form.setUserDetail(byId);

        }
        return Result.success(list);
    }

    /**
     * 新增数据
     *
     * @param commentForm 实例对象
     * @return 实例对象
     */
    @Operation(summary = "新增数据")
    @PostMapping("/insert")
    public Result<Boolean> insert(@RequestBody CommentForm commentForm) {
        if (commentFormService.save(commentForm)) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 更新数据
     *
     * @param commentForm 实例对象
     * @return 实例对象
     */
    @Operation(summary = "更新数据")
    @PutMapping("update")
    public Result<Boolean> update(@RequestBody CommentForm commentForm) {
        if (commentFormService.updateById(commentForm)) {
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Operation(summary = "通过主键删除数据", parameters = {@Parameter(name = "id", description = "主键", required = true, in = ParameterIn.PATH)})
    @DeleteMapping("/delete/{id}")
    public Result<Boolean> deleteById(@PathVariable String id) {

        if (commentFormService.removeById(id)) {
            return Result.success();
        }
        return Result.error();
    }

    @Operation(summary = "多id删除数据")
    @DeleteMapping("/delete")
    public Result<Boolean> deleteByIds(@RequestBody List<String> id) {
        log.info("前端信息：{}", id);
        if (commentFormService.removeByIds(id)) {
            return Result.success();
        }
        return Result.error();
    }
}